package com.linsen.core.common.convert.factory;

import com.linsen.core.common.convert.StringToEnumConverter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 解决前后端交互Form表单提交枚举参数值的转换问题
 *   特别指出：枚举类中@JsonValue指定json序列化的字段；@JsonCreator指定json反序列化的值转换为枚举
 */
public class StringToEnumConverterFactory implements ConverterFactory<String, Enum> {
    private static final Map<Class, Converter> CONVERTER_MAP = new ConcurrentHashMap<>();

    @Override
    public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
        Converter converter = CONVERTER_MAP.get(targetType);
        if (converter == null) {
            converter = new StringToEnumConverter<>(targetType);
            CONVERTER_MAP.put(targetType, converter);
        }
        return converter;
    }
}
